
#import "XMUploadManager.h"
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
#import "XMAppConfigViewModel.h"
#import "XMCOSConfigModel.h"
#import "XMUploadResultModel.h"

@interface XMUploadManager () <QCloudSignatureProvider>
@property (nonatomic, strong) XMAppConfigViewModel *viewModel;
@property (nonatomic, strong) XMCOSConfigModel *config;
@end


@implementation XMUploadManager

+ (XMUploadManager *)sharedInstance {
    static XMUploadManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)setupCOSXMLShareService {
    XMWeakSelf(self);
    [self getConfigComplete:^(XMCOSConfigModel *config) {
        XMStrongSelf(self);
        self.config = config;
        QCloudServiceConfiguration *configuration = [[QCloudServiceConfiguration alloc] init];
        QCloudCOSXMLEndPoint *endpoint = [[QCloudCOSXMLEndPoint alloc] init];
        endpoint.regionName = config.Region;
        configuration.endpoint = endpoint;
        configuration.signatureProvider = self;
        configuration.isCloseShareLog = YES;
        [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
        [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];
    }];
}

- (void)signatureWithFields:(QCloudSignatureFields *)fileds
                    request:(QCloudBizHTTPRequest *)request
                 urlRequest:(NSMutableURLRequest *)urlRequst
                  compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock {
    XMWeakSelf(self);
    [self getConfigComplete:^(XMCOSConfigModel *config) {
        XMStrongSelf(self);
        self.config = config;
        QCloudCredential *credential = [QCloudCredential new];
        credential.secretID = config.Credentials.TmpSecretId;
        credential.secretKey = config.Credentials.TmpSecretKey;
        credential.token = config.Credentials.Token;
        credential.startDate = [NSDate dateWithTimeIntervalSince1970:config.RequestTime.doubleValue];
        credential.expirationDate = [NSDate dateWithTimeIntervalSince1970:config.ExpiredTime.doubleValue];
        QCloudAuthentationV5Creator *creator = [[QCloudAuthentationV5Creator alloc] initWithCredential:credential];
        
        QCloudSignature *signature = [creator signatureForData:urlRequst];
        continueBlock(signature, nil);
    }];
}

- (void)uploadImageArray:(NSArray<UIImage *> *)imageArray
               person_id:(NSString *)person_id
                complete:(void (^)(NSMutableArray<XMUploadResultModel *> *array))complete {
    __block NSMutableArray<XMUploadResultModel *> *results = [NSMutableArray array];
    dispatch_group_t group = dispatch_group_create();
    [imageArray enumerateObjectsUsingBlock:^(UIImage *_Nonnull image, NSUInteger idx, BOOL *_Nonnull stop) {
        dispatch_group_enter(group);
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        __block XMUploadResultModel *model = [[XMUploadResultModel alloc] init];
        model.imgW = image.size.width;
        model.imgH = image.size.height;
        model.imgSize = imageData.length;
        model.index = idx;
        QCloudCOSXMLUploadObjectRequest *upload = [[QCloudCOSXMLUploadObjectRequest alloc] init];
        upload.bucket = self.config.Bucket;
        upload.object = kStringFormat(@"%@/%@/%@/%@.webp", @"XunMi", person_id, [NSDate xm_stringCurrentDateWithDateFormat:@"yyyyMMdd"], [NSDate xm_getCurrentTimeIntervalWithLenght:13]);
        upload.body = imageData;
        upload.regionName = self.config.Region;
        [upload setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
            NSString *fileUrl = result.location;
            if (!error) {
                model.url = fileUrl;
                model.success = YES;
            } else {
                model.url = @"";
                model.success = NO;
            }
            NSString *server = [[result __originHTTPURLResponse__].allHeaderFields valueForKey:@"Server"];
            model.server = server.length > 0 ? server : @"tencent-cos";
            [results addObject:model];
            dispatch_group_leave(group);
        }];
        
        [upload setSendProcessBlock:^(int64_t bytesSent,
                                      int64_t totalBytesSent,
                                      int64_t totalBytesExpectedToSend){}];
        
        [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:upload];
    }];
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        complete(results);
    });
}

- (void)uploadWithFilePath:(NSString *)filePath
                      type:(XMUploadType)type
                 person_id:(NSString *)person_id
                  complete:(void (^)(XMUploadResultModel *result))complete {
    XMUploadResultModel *model = [[XMUploadResultModel alloc] init];
    NSString *file = @"";
    switch (type) {
        case XMUploadTypeImage:
            file = kStringFormat(@"%@/%@/%@/%@.webp", @"XunMi", person_id, [NSDate xm_stringCurrentDateWithDateFormat:@"yyyyMMdd"], [NSDate xm_getCurrentTimeIntervalWithLenght:13]);
            break;
        case XMUploadTypeAudio:
            file = kStringFormat(@"%@/%@/%@/%@.m4a", @"XunMi", person_id, [NSDate xm_stringCurrentDateWithDateFormat:@"yyyyMMdd"], [NSDate xm_getCurrentTimeIntervalWithLenght:13]);
            break;
        case XMUploadTypeVideo:
            file = kStringFormat(@"%@/%@/%@/%@.mp4", @"XunMi", person_id, [NSDate xm_stringCurrentDateWithDateFormat:@"yyyyMMdd"], [NSDate xm_getCurrentTimeIntervalWithLenght:13]);
            break;
        default:
            break;
    }
    QCloudCOSXMLUploadObjectRequest *upload = [[QCloudCOSXMLUploadObjectRequest alloc] init];
    upload.bucket = self.config.Bucket;
    upload.object = file;
    upload.body = [NSURL fileURLWithPath:filePath];
    upload.regionName = self.config.Region;
    
    [upload setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
        
        NSString *fileUrl = result.location;
        if (!error) {
            model.url = fileUrl;
            model.success = YES;
        } else {
            model.url = @"";
            model.success = NO;
        }
        NSString *server = [[result __originHTTPURLResponse__].allHeaderFields valueForKey:@"Server"];
        model.server = server.length > 0 ? server : @"tencent-cos";
        dispatch_async(dispatch_get_main_queue(), ^{
            complete(model);
        });
    }];
    
    
    [upload setSendProcessBlock:^(int64_t bytesSent,
                                  int64_t totalBytesSent,
                                  int64_t totalBytesExpectedToSend){
        
        
        
    }];
    
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:upload];
}

- (void)uploadImage:(UIImage *)image
           compress:(BOOL)compress
          person_id:(NSString *)person_id
           complete:(void (^)(XMUploadResultModel *result))complete {
    NSData *imageData = UIImageJPEGRepresentation(image, compress ? .4 : 1);
    XMUploadResultModel *model = [[XMUploadResultModel alloc] init];
    model.imgW = image.size.width;
    model.imgH = image.size.height;
    model.imgSize = imageData.length;
    QCloudCOSXMLUploadObjectRequest *upload = [[QCloudCOSXMLUploadObjectRequest alloc] init];
    upload.bucket = self.config.Bucket;
    upload.object = kStringFormat(@"%@/%@/%@/%@.webp", @"XunMi", person_id, [NSDate xm_stringCurrentDateWithDateFormat:@"yyyyMMdd"], [NSDate xm_getCurrentTimeIntervalWithLenght:13]);
    upload.body = imageData;
    upload.regionName = self.config.Region;
    [upload setFinishBlock:^(QCloudUploadObjectResult *result, NSError *error) {
        NSString *fileUrl = result.location;
        if (!error) {
            model.url = fileUrl;
            model.success = YES;
        } else {
            model.url = @"";
            model.success = NO;
        }
        NSString *server = [[result __originHTTPURLResponse__].allHeaderFields valueForKey:@"Server"];
        model.server = server.length > 0 ? server : @"tencent-cos";
        dispatch_async(dispatch_get_main_queue(), ^{
            complete(model);
        });
    }];
    
    [upload setSendProcessBlock:^(int64_t bytesSent,
                                  int64_t totalBytesSent,
                                  int64_t totalBytesExpectedToSend){
        
        
        
    }];
    
    [[QCloudCOSTransferMangerService defaultCOSTransferManager] UploadObject:upload];
}

- (void)getConfigComplete:(void (^)(XMCOSConfigModel *config))complete {
    [self.viewModel getCOSConfigCompleteBlock:^(XMResponseTip *_Nonnull tip, XMCOSConfigModel *_Nullable result) {
        if (tip.success) {
            complete(result);
        }
    }];
}

- (NSString *)piyinString:(NSString *)string {
    NSString *piyinStr = @"";
    NSMutableString *mutableString = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformStripDiacritics, false);
    if (CFStringTransform((__bridge CFMutableStringRef)(mutableString), NULL, (__bridge CFStringRef) @"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
        piyinStr = [mutableString stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    return piyinStr;
}

- (XMAppConfigViewModel *)viewModel {
    if (_viewModel == nil) {
        _viewModel = [[XMAppConfigViewModel alloc] init];
    }
    return _viewModel;
}

@end
